package com.zut.blocks.web.controller;

import com.zut.blocks.base.common.CommonResponse;
import com.zut.blocks.base.common.Login;
import com.zut.blocks.base.controller.GenericController;
import com.zut.blocks.base.domain.User;
import com.zut.blocks.base.util.UserUtil;
import com.zut.blocks.service.user.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Author lvxin
 * @Date 2020/12/22 9:38
 */
@Controller
public class LoginController extends GenericController<User, Integer, UserService> {

    @Resource
    UserService userService;

    @ResponseBody
    @PostMapping(value = "/login")
    public CommonResponse<String> login(HttpSession session, String username, String password) {
        Login login = userService.login(username, password);
        session.setAttribute(UserUtil.KEY_USER, login);
        session.setAttribute("version", String.valueOf(System.currentTimeMillis()));
        return CommonResponse.success("/user/" + login.getType().name());
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return "redirect:/";
    }

}
